 <?php

class OrderCompletedUpload extends Controller {

	public function index() {

	}

	public function upload( $filepath ) {
		$errors = [];

		$csv = fopen( $filepath, 'r' );

		$ctr = 0;
		while ( ( $data = fgetcsv($csv, 1000, ",") ) !== FALSE ) {
			
			if($ctr > 0 ) {
				$id			= $data[0];
				$dr_number	= $data[1];
				$dr_date	= $data[2];

				$order_product = OrderProduct::select( DB::raw('*, company.code AS `COMPANY_code`') )
									->join('order', 'ORDER_id', '=', 'order.id')
									->join('company', 'COMPANY_id', '=', 'company.id')
									->where( 'order_product.id', '=', (int)$id )->first();
				
				if( empty($order_product->id) )
					$errors[] = $id . ' ' . Lang::get('upload.error_order_product_not_exist');
				else {
					if( !empty( trim($order_product->dr_number) ) )
						$errors[] = $dr_number .  ' '.  Lang::get('upload.error_dr_number_exist') . ' ' . $order_product->dr_number;
				}

				if( empty( $dr_number ) )
						$errors[] = Lang::get('upload.error_dr_number');	

				if( empty( $dr_date ) )
						$errors[] = Lang::get('upload.error_dr_date');

				if( !$errors ) {
					try {
						$data = [ 'status' => Constant::ORDER_DELIVERED, 'dr_number' => $dr_number, 'dr_date' => $dr_date ];

						Webservice::post( Config::get('app.api') . $order_product->COMPANY_code . '/order_product/move-to-delivered-status' , [ 'id' => $id, 'result' => $data ] );
						OrderProduct::where( 'id', '=', $id )->update( $data );
					}
					catch(Exception $ex) {
						
					}
				}
			}

			$ctr++;
		}

		if( $errors ) {
			Mail::send('emails.upload', [ 'errors' => $errors ],  function($message){
				$message->to(Auth::user()->email, Auth::user()->firstname)->subject('Errors: Move to Delivered Status ' . date('Y-m-d h:i:s'));
			});
		}

		return $errors;
	}
}